<?php

namespace app\common\service;

use think\facade\Db;
use org\SocialLogin\SocialOauth;
use app\api\controller\Base;
/**
 * @author 基础小组
 * @group description=账号绑定
 */
class Weixin extends Base
{
    public $GetRequestCodeURL = 'https://open.weixin.qq.com/connect/oauth2/authorize';
    /**
     * @description 获取请求code用的url
     * @param string $type 类型(weixin微信|qq腾讯QQ|douyin抖音) 必须
     * @param string $scope 授权作用域(默认0显式授权|1静默授权) 可选
     * @param array $params 额外参数 可选
     * @param string $url 三方登录后的回调地址 可选
     * @return string
     */
    public function index()
    {
        $type = 'weixin'; //三方登录类型

        $callback = input('callback');
        $params = input('params');
        $url = input('url');
        if($url) {
            $_flag = md5($url);
            if(!$params) {
                $params = [];
            }
            $params['url'] = $_flag;
            //缓存
            cache($_flag, $url);
        }
        //静默授权
        $scope = input('scope') ? 'snsapi_base' : 'snsapi_userinfo';
         if('snsapi_base' == $scope) {
             $params['si'] = '1';
         }

        //生成请求code的url
        $url = $this->getRequestCodeURL($scope, $callback, $params);

        return $url;
    }
    /**
     * 请求code
     */
    public function getRequestCodeURL($scope = '', $callback = '', $params_arr = [])
    {
        // Oauth 标准参数

            //授权方式(默认主动授权)
            if(!$scope || !in_array($scope, ['snsapi_userinfo', 'snsapi_base'])) {
                $scope = 'snsapi_userinfo';
            };
            //回调地址
            $callback = $callback ?: $this->Callback;
            if($params_arr && is_array($params_arr)) {
                //业务参数(附加到回调地址后)
                foreach($params_arr as $_k => $_v) {
                    $callback .= '/'.$_k.'/'.$_v;
                }
            }
            //请求参数
            $params = array(
                'appid' => $this->AppKey,
                'redirect_uri' => $callback ?: $this->Callback,
                'response_type' => 'code',
                'scope' => $scope,
                'state' => 'oauth'
            );

        return $this->GetRequestCodeURL.'?'.http_build_query($params).'#wechat_redirect';
    }
}